# -*- coding: UTF-8 -*-


import urllib
import Book


def get_book_xxx_list(file_name):
    """
    获取目标图书列表
    :return: list
    """
    file_obj = open(file_name, "r")
    lines = file_obj.readlines()
    target_list = list()
    for line in lines:
        book_name = line.strip()
        if len(book_name) == 0 or book_name.startswith('#'):
            continue
        try:
            book_name = book_name[book_name.index('《')+3: book_name.index('》')]
        except Exception:
            pass
        target_list.append(book_name)
    return target_list


def get_sale_book_list():
    """
    获取优惠图书列表
    :return: list
    """
    # 读取页面内容
    url = "http://t.bookdna.cn/"
    conn = urllib.urlopen(url)
    page_content = conn.read()
    conn.close()

    # 解析页面，获取特价书列表
    sale_book_list = list()
    split_string = "<div style='margin-bottom: 0.9em;'>"
    for item in page_content[page_content.index(split_string) + len(split_string):].split(split_string):
        name = item[item.index("title='") + len("title='"):item.index("' target='_blank'><b>")]
        author = item[item.index("</span></span><div style='margin-top: 0.3em;color:#008000; font-size:0.9em'>作者：") + len("</span></span><div style='margin-top: 0.3em;color:#008000; font-size:0.9em'>作者："):item.index("，评分：")]
        score = item[item.index("，评分：")+len("，评分："):item.index("，<span title='最近在")]
        avg_price = item[item.index("历史均价：￥")+len("历史均价：￥"):item.index("，<span title='相当于")]
        sale_price = item[item.index("'>现价：<span style='color:#FF7237'>￥") + len("'>现价：<span style='color:#FF7237'>￥"):item.index("</span></span><div style='margin-top: 0.3em;color:#008000; font-size:0.9em'>作者：")]
        if "<span style='color:#5a5a5a'>" in item:
            min_price = item[item.index("达到最低价'>历史最低价：￥")+len("达到最低价'>历史最低价：￥"):item.index("</span></div></div>")]
        elif "</span></div></div>----------------------------" in item:
            min_price = item[item.index("达到最低价'>历史最低价：￥")+len("达到最低价'>历史最低价：￥"):item.index("</span></div></div>----------------------------")]
        url = item[item.index("</span>  <a href='")+len("</span>  <a href='"):item.index("title='")-6]
        book_item = Book.Book(name, author, score, avg_price, sale_price, min_price, url)
        sale_book_list.append(book_item)
    return sale_book_list


if __name__ == "__main__":
    # sale_book_list = get_sale_book_list()
    # for i in range(0, len(sale_book_list)):
    #     book = sale_book_list[i]
    #     print i, "  ", book.name, "  ", book.author, "  ", book.score, "  ", book.avg_price, "  ", book.sale_price, "  ", book.min_price, "  ", book.url

    book_xxx_list = get_book_xxx_list(r'./data/book-demand.data')
    for i in range(0, len(book_xxx_list)):
        book = book_xxx_list[i]
        print i, "  ", book
else:
    pass




